<?php

namespace Fox;

require_once 'func.php';

class Boot {

	public $route;
	public $config;

	public $appPath;
	public $viewPath;
	public $controllerPath;
	public $modelPath;
	public $confPath;

	public function run() {
		$this->loadIniFile();
		$this->route->route();
	}

	private function __construct($path) {
		$this->loadConfig($path);
	}

	private function loadIniFile() {
		if (isset($this->config['start_files'])) {
			foreach ($this->config['start_files'] as $item) {
				L(combine_paths(ROOT, $item));
			}
		}
	}


	public function registerErrorHandle($config){
		$type = $config['type'];
		$type_obj = new $type($config['pars']);
		$type_obj->register();
	}

	public function loadConfig($path) {

		$this->config = L(combine_paths(ROOT, $path));

		if ($this->config['error']) {
			$this->registerErrorHandle($this->config['error']);
		}

		$mvcConfig = $this->config['mvc'];

		$this->appPath = combine_paths(ROOT, $this->config['app_path']);
		$this->viewPath = combine_paths($this->appPath, $mvcConfig['view_path']);
		$this->controllerPath = combine_paths($this->appPath, $mvcConfig['controller_path']);
		$this->modelPath = combine_paths($this->appPath, $mvcConfig['model_path']);
		$this->confPath = combine_paths($this->appPath, $this->config['conf_path']);

		$mvcConfig['app_path'] = $this->config['app_path'];
		$mvcConfig['full_app_path'] = $this->appPath;
		$mvcConfig['route'] = isset($this->config['route']) ? $this->config['route'] : [];

		$this->route = new Route($mvcConfig);

	}

	private static $instance;
	
	public static function getInstance($path = null) {
		if (!self::$instance) {
			self::$instance = new Boot($path);
		}
		return self::$instance;
	}

	public function rewrite($url) {
		$this->route->route($url);
	}

}
